//
//  TSCVCGuideBizList.m
//  Tsc_IOS
//
//  Created by Rio on 15-9-24.
//  Copyright (c) 2015年 idream. All rights reserved.
//

#import "TSCSDK.h"
#import "TSCVCGuideBizList.h"
#import "TSCVCGuideBizListPage.h"


@implementation TSCVCGuideBizList {
    NSInteger _userId;
    
    DKTabPageViewController * _tpvc; // 分页控制器
    TSCVCGuideBizListPage * _vcCustomerWantBuy;
    TSCVCGuideBizListPage * _vcCustomerQ;
    
    TSCMySidebar * _msbQueryPanel; // 搜索面板
    TSCFragMSBSearchGuideBiz * _fragSearchGuideBiz;
    
    TSCMySidebar * _msbDatepicker; // 日期选择面板
    TSCMyDatePicker * _mdpQueryDate; // 日期选择器
}

//#pragma mark 校验并获取输入
//
//- (void) getVCInput:(NSNotificationCenter *)notification {
//    [super getVCInput:notification];
//
//    _iGuideId = [[_inputDic objectForKey:AEKI_GUIDE_ID] integerValue];
//}


+ (id)vcGuideBizListWithStoryboard {
    UIStoryboard * sb = [UIStoryboard storyboardWithName:UI_STORYBOARD_NAME_MAIN bundle:[NSBundle mainBundle]];
    return [sb instantiateViewControllerWithIdentifier:UI_VC_NAME_GUIDE_BIZ_LIST];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    // 初始化类属性
    _userId = [[_ud objectForKey:UD_USER_ID] integerValue];
    
    // == 设置自定义导航栏
    _nbc = [[TSCMyNaviBarCreator alloc]initAndCreateWithViewController:self hasGoBackButton:YES goBackVC:nil hasAppLogo:YES titleResourceKey:@"app_name" iconResourceNameArray:[NSArray arrayWithObjects:@"ic_search_96x96.png", @"ic_trash_96x96.png", nil] iconClickedListenerArray:
            [NSArray arrayWithObjects:
             // 注册事件——打开侧边栏搜索面板
             ^(UIButton * btn){
                 if (_msbQueryPanel.isPresenting == NO) {
                     [_msbQueryPanel presentAnimated:YES completion:nil];
                 } else {
                     [_msbQueryPanel dismissAnimated:YES completion:nil];
                 }
             },
             // 注册事件——删除全部未读消息
             // 注：需要copy block
             [^(UIButton * btn) {
                 UIAlertView * av = [[UIAlertView alloc]initWithTitle:NSLocalizedString(@"title_confirm_delete", nil) message:NSLocalizedString(@"title_confirm_del_all_unprocessed_msg", nil) delegate:self cancelButtonTitle:NSLocalizedString(@"btn_cancel", nil) otherButtonTitles:NSLocalizedString(@"btn_confirm", nil), nil];
                 [av show];
             } copy],
             nil]
            ];
    
    // == 创建tabPage
    self.automaticallyAdjustsScrollViewInsets = NO; // 注：必须要加上此句，否则会导致tabPageBar以下的部分显示混乱
    _vcCustomerWantBuy = [TSCVCGuideBizListPage vcGuideBizListPageWithStoryboardWithType:TSCVCGuideBizListPageTypeCustomerWantBuy];
    DKTabPageItem *itemCustomerWantBuy = [DKTabPageViewControllerItem tabPageItemWithTitle:NSLocalizedString(@"title_tab_customer_want_buy", nil) viewController:_vcCustomerWantBuy];
    _vcCustomerQ = [TSCVCGuideBizListPage vcGuideBizListPageWithStoryboardWithType:TSCVCGuideBizListPageTypeCustomerQ];
    DKTabPageItem *itemCustomerQA = [DKTabPageViewControllerItem tabPageItemWithTitle:NSLocalizedString(@"title_tab_customer_q", nil) viewController:_vcCustomerQ];
    NSArray *itemArr = [NSArray arrayWithObjects:itemCustomerWantBuy, itemCustomerQA, nil];
    
    _tpvc = [[DKTabPageViewController alloc] initWithItems:itemArr];
    _tpvc.showTabPageBar = YES;
    _tpvc.tabPageBar.titleFont = [TSCMyUIUtil getSystemDefaultFont];
    _tpvc.tabPageBar.titleColor = COLOR_MT;
    _tpvc.tabPageBar.selectedTitleColor = COLOR_MT;
    _tpvc.tabPageBar.selectedIndicatorColor = COLOR_MT;
    _tpvc.contentInsets = UIEdgeInsetsMake(
                                           // 注：需要加上statusBar、naviBar的高度，作为inset
                                           [TSCMyUIUtil getStatusBarFrame].size.height // 22
                                           +
                                           [TSCMyUIUtil getNavigationBarFrame:self].size.height // 44
                                           ,
                                           0,
                                           0, // 例子中是：49，感觉没用，改成0
                                           0);
    [self addChildViewController:_tpvc];
    [self.view addSubview:_tpvc.view];
    
    
    // == 创建搜索栏
    _msbQueryPanel= [[TSCMySidebar alloc]init];
    _msbQueryPanel.vcMain = self;
    _msbQueryPanel.presentStyle = TSCSidebarPresentStyleFlyFromLeft;
    _msbQueryPanel.hasBGColor = NO;
    _msbQueryPanel.hasRoundCorner = NO;
    _msbQueryPanel.hasShadow = YES;
    _msbQueryPanel.hasBorder = NO;
    _msbQueryPanel.bgClickedDismissAnimated = YES;
    _msbQueryPanel.bgClickedDismissCompletion = ^() {
        // do nothing
    };
    _msbQueryPanel.dialogWType = TSCSidebarDialogWHTypePrefer;
    _msbQueryPanel.dialogHType = TSCSidebarDialogWHTypePrefer;
    _msbQueryPanel.dialogCustomViewSizePosition = TSCSideBarDialogCustomViewSizePositionFillParent;
    
    _fragSearchGuideBiz = [TSCFragMSBSearchGuideBiz loadFromXib];
    _fragSearchGuideBiz.tfDate.delegate = self; // 阻止弹出键盘
    [TSCMyUIUtil addDownTriangleIconToView:_fragSearchGuideBiz.tfDate direction:IconDirectionRight];
    _msbQueryPanel.customView = _fragSearchGuideBiz;
    
    // 注册事件——点击弹出日期选择框
    [_fragSearchGuideBiz.tfDate addTarget:self action:@selector(tfMSBSelectDateClicked) forControlEvents:UIControlEventTouchDown];
    // 注册事件——点击搜索按钮
    [_fragSearchGuideBiz.btnQuery addTarget:self action:@selector(btnMSBQueryClicked) forControlEvents:UIControlEventTouchUpInside];
    
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
 {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

#pragma mark delegate

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    return NO; // 点击textField自身时，阻止键盘弹出
}

- (void) tfMSBSelectDateClicked {
    
    // 创建日期选择面板
    _msbDatepicker = [[TSCMySidebar alloc]init];
    _msbDatepicker.vcMain = self;
    _msbDatepicker.presentStyle = TSCSidebarPresentStyleFlyFromBottom;
    _msbDatepicker.hasBGColor = NO;
    _msbDatepicker.hasRoundCorner = NO;
    _msbDatepicker.hasShadow = YES;
    _msbDatepicker.hasBorder = NO;
    _msbDatepicker.bgClickedDismissAnimated = YES;
    _msbDatepicker.bgClickedDismissCompletion = ^() {
        // do nothing
    };
    _msbDatepicker.dialogWType = TSCSidebarDialogWHTypeDynamic;
    _msbDatepicker.dialogHType = TSCSidebarDialogWHTypeDynamic;
    _msbDatepicker.dialogCustomViewSizePosition = TSCSideBarDialogCustomViewSizePositionFillParent;
    
    // 创建日期选择器
    _mdpQueryDate = [TSCMyDatePicker loadFromXib];
    _mdpQueryDate.datePickerMode = UIDatePickerModeDate;
    _mdpQueryDate.initialDate = [TSCMyUtil isStringEmpty:_fragSearchGuideBiz.tfDate.text] == NO ? [[self constructDateFormatter] dateFromString:_fragSearchGuideBiz.tfDate.text] : [NSDate date]; // 计算初始日期：如果曾经选择了某个日期，就以这个日期为初始日期；如果以前没有选择过任何日期，就以当前日期为初始日期
    
    __weak typeof (self) _weakSelf = self;
    _mdpQueryDate.btnClickedListenerConfirm = ^(UIButton * btn, NSDate * date) {
        typeof (self) _strongSelf = _weakSelf;
        if (_strongSelf) {
            // 显示选择的日期
            _strongSelf->_fragSearchGuideBiz.tfDate.text = [[_strongSelf constructDateFormatter] stringFromDate:date];
            
            // 关闭日期选择窗口
            [_strongSelf->_msbDatepicker dismissAnimated:YES completion:nil];
        }
    };
    _mdpQueryDate.btnClickedListenerCancel = ^(UIButton * btn, NSDate * date) {
        typeof (self) _strongSelf = _weakSelf;
        if (_strongSelf) {
            // 关闭日期选择窗口
            [_strongSelf->_msbDatepicker dismissAnimated:YES completion:nil];
        }
    };
    _mdpQueryDate.btnClickedListenerNoSelect = ^(UIButton * btn, NSDate * date) {
        typeof (self) _strongSelf = _weakSelf;
        if (_strongSelf) {
            // 清除选择的日期
            _strongSelf->_fragSearchGuideBiz.tfDate.text = @"";
            
            // 关闭日期选择窗口
            [_strongSelf->_msbDatepicker dismissAnimated:YES completion:nil];
        }
    };
    _msbDatepicker.customView = _mdpQueryDate;
    
    // 显示日期选择面板
    [_msbDatepicker presentAnimated:YES completion:nil];
}

- (void) btnMSBQueryClicked {
    // 关闭查询面板
    [_msbQueryPanel dismissAnimated:YES completion:nil];
    
    
    // NSString * dateStr = [TSCMyUtil date2String:[TSCMyUtil string2Date:_fragSearchGuideBiz.tfDate.text format:@"yyyy年MM月dd日"] format:@"yyyyMMdd"];
    NSString * dateStr = [TSCMyUtil date2String:_mdpQueryDate.selectedDate format:@"yyyyMMdd"];
    NSString * customerName = [TSCMyUtil trim:_fragSearchGuideBiz.tfCustomerName.text];
    NSLog(@"dateStr:%@, customerName:%@", dateStr, customerName);
    NSLog(@"date1:%@, date2:%@", _mdpQueryDate.selectedDate, _mdpQueryDate.datePicker.date);
    
    // 重新查询
    _vcCustomerWantBuy.queryDateStr = dateStr;
    _vcCustomerWantBuy.queryCustomerName = customerName;
    [_vcCustomerWantBuy requery:YES];
    
    _vcCustomerQ.queryDateStr = dateStr;
    _vcCustomerQ.queryCustomerName = customerName;
    [_vcCustomerQ requery:YES];
    
}

#pragma mark 私有方法

- (NSDateFormatter *) constructDateFormatter {
    NSDateFormatter * df = [[NSDateFormatter alloc]init];
    df.dateFormat = @"yyyy年MM月dd日";
    return df;
}

#pragma mark UIAlertViewDelegate
//根据被点击按钮的索引处理点击事件
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    
    // 0 == 取消
    if (buttonIndex == 0) {
        // do nothing
    }
    // 1 == 确定
    else if (buttonIndex == 1) {
        [TSCMyDBUtil deleteAllUnreadMsgWithUserId_1:_userId];
    }
    
}

@end
